package com.foreveross.proxyip.infra;

import java.lang.reflect.InvocationTargetException;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.foreveross.proxyip.entity.IpStoreEntity;
import com.foreveross.proxyip.entity.RetrieveIpEntity;
import com.foreveross.proxyip.exception.ProxyIpServiceException;
import com.foreveross.proxyip.infra.base.ddd.domain.IBaseEntity;
import com.foreveross.proxyip.infra.base.ddd.repository.EntityHibernateRepository;
import com.foreveross.proxyip.infra.base.ddd.repository.IBaseRepository;
import com.foreveross.proxyip.infra.cache.BufferInstance;
import com.foreveross.proxyip.infra.cache.Operations;
@SuppressWarnings({"unchecked","rawtypes"})
@Repository("cacheEntityRepository")
public class CacheEntityRepository extends EntityHibernateRepository implements IBaseRepository {

	protected static Logger logger = Logger.getLogger(CacheEntityRepository.class);

	
	
	
	@Transactional
	public synchronized void transSaveList(List list) {
		List<BufferInstance> bufferInstance = list;
		try {
				for(BufferInstance bi : bufferInstance) {
					IBaseEntity entity = (IBaseEntity)bi.getInstance();
					if(bi.getOper().equals(Operations.CREATE)) {
						if(entity instanceof IpStoreEntity){
							IpStoreEntity ipStoreEntity =(IpStoreEntity) entity ;
							Object []params = {ipStoreEntity.getIp()};
							List a = this.queryResult("from IpStoreEntity t where t.ip=?", params);
							if(a==null||a.size()==0){
								create(ipStoreEntity);
							}
						}else if(entity instanceof RetrieveIpEntity){
							RetrieveIpEntity retrieveIpEntity =(RetrieveIpEntity) entity ;
							transferHistory(retrieveIpEntity);
						}else{
							create(entity);
						}
					}else if(bi.getOper().equals(Operations.UPDATE)) {
						update(entity);
					}else if(bi.getOper().equals(Operations.DELETE)) {
						delete(entity);
					}
				}
	} catch (Exception e) {
		ProxyIpServiceException.getStackTrace(e);
	}finally{
		bufferInstance.clear();
		bufferInstance =null;
	}

	}
	
	public void transferHistory(RetrieveIpEntity entity) throws IllegalAccessException, InvocationTargetException{
		String queryStr = "from RetrieveIpEntity t where t.ip = ?";
		List<RetrieveIpEntity> retrieveList = this.queryResult(queryStr, new Object[]{entity.getIp()});
		for(RetrieveIpEntity retrieve : retrieveList){
			  this.save(retrieve.toHistoryIpEntity());
			  this.delete(retrieve);
		}
		this.create(entity);
	}
	

}
